package com.study.www.config;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

public abstract class AbstractQuartzJob implements Job {
    private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);
    /**
     * 线程本地变量
     */
    private static ThreadLocal<Date> threadLocal = new ThreadLocal<>();

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Object sysJob = new Object();
        try{
            before(jobExecutionContext, sysJob);
            if (sysJob != null)
            {
                doExecute(jobExecutionContext, sysJob);
            }
            after(jobExecutionContext, sysJob, null);
        }
        catch (Exception e)
        {
            log.error("任务执行异常  - ：", e);
            after(jobExecutionContext, sysJob, e);
        }
    }
    /**
     * 执行前
     *
     * @param context 工作执行上下文对象
     * @param object 系统计划任务
     */
    protected void before(JobExecutionContext context, Object object)
    {
        log.info("开始执行任务前。。。");
        threadLocal.set(new Date());
    }
    /**
     * 执行后
     *
     * @param context 工作执行上下文对象
     * @param object 系统计划任务
     */
    protected void after(JobExecutionContext context,Object object, Exception e){
        Date startTime = threadLocal.get();
        threadLocal.remove();
        //开始到结束任务的日志信息（如时间，处理数据数量等）...
        log.info("任务执行结束：{}");
    }
    /**
     * 执行方法，由子类重载
     *
     * @param context 工作执行上下文对象
     * @param object 系统计划任务
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, Object object) throws Exception;
}
